package com.cicadasmall.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cicadasmall.common.base.BaseService;
import com.cicadasmall.common.func.Fn;
import com.cicadasmall.data.domain.RoleDO;
import com.cicadasmall.data.domain.UserRoleDO;
import com.cicadasmall.data.mapper.SysUserRoleMapper;
import com.cicadasmall.system.service.IRoleService;
import com.cicadasmall.system.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 用户角色管理表 服务实现类
 * </p>
 *
 * @author westboy
 * @date 2019-07-21
 */
@Service
public class UserRoleServiceImpl extends BaseService<SysUserRoleMapper, UserRoleDO> implements IUserRoleService {
    @Autowired
    private IRoleService roleService;

    @Override
    public List<UserRoleDO> findByUserId(Serializable uid) {
        return baseMapper.selectList(getLambdaQueryWrapper().eq(UserRoleDO::getUid,uid));
    }

    @Override
    public void updateUserRole(Integer uid, List<String> roleIds) {
        if(Fn.isNotEmpty(roleIds)){

            LambdaQueryWrapper lambdaQueryWrapper = getLambdaQueryWrapper().eq(UserRoleDO::getUid, uid);
            Integer count = baseMapper.selectCount(lambdaQueryWrapper);

            if(count>0){
                baseMapper.delete(lambdaQueryWrapper);
            }

            roleIds.forEach(roleId->{
                RoleDO role =  roleService.getById(roleId);
                if(role!=null){
                    UserRoleDO userRoleDO = new UserRoleDO();
                    userRoleDO.setRoleId(role.getRoleId());
                    userRoleDO.setUid(uid);
                    baseMapper.insert(userRoleDO);
                }
            });
        }
    }
}
